<script lang="ts" setup>
    import { defineComponent,reactive,ref } from 'vue'
    import {
        UploadFile,
        UploadRawFile,
        ElRow,
        ElCol,
        ElUpload,
        ElIcon,
        ElForm,
        ElFormItem,
        ElInput,
        ElButton,
        ElMessage,
        FormInstance
    } from 'element-plus'
    import { InputPassword } from '@/components/InputPassword'
    import type { UploadProps } from 'element-plus'
    import { useDesign } from '@/hooks/web/useDesign'
    import { useValidator } from '@/hooks/web/useValidator'
    import { useForm } from '@/hooks/web/useForm'

    import {uppassword,mainImage} from '@/api/login'
    const { register, elFormRef } = useForm()
    const { required } = useValidator()
    const { getPrefixCls } = useDesign()
    const prefixCls = getPrefixCls('panel')
    const imageUrl = ref('')
    const ruleFormRef = ref<FormInstance>()
    /* 密码 */
    const validatePass = (rule: any, value: any, callback: any) => {
        if (value === '') {
            callback(new Error('请输入密码'))
        } else {
            if (ruleForm.checkPass !== '') {
                if (!ruleFormRef.value) return
                ruleFormRef.value.validateField('checkPass', () => null)
            }
            callback()
        }
    }
    /* 如果密码输入的不正确，需要重新输入 */
    const validatePass2 = (rule: any, value: any, callback: any) => {
        if (value === '') {
            callback(new Error('请重新输入密码'))
        } else if (value !== ruleForm.pass) {
            callback(new Error("两个输入不匹配！"))
        } else {
            callback()
        }
    }
    /* 传入的值 */
    var user = sessionStorage.getItem("user");
    var userdui = JSON.parse(user);
    /* 账户的属性 */
    const ruleForm = reactive({
        name:userdui.account,
        Email:userdui.email,
        pass: '',
        checkPass: '',
        //userId: ''
    })
    /* 触发表单验证 */
    const rules = reactive({
        pass: [{ validator: validatePass, trigger: 'blur' }],
        checkPass: [{ validator: validatePass2, trigger: 'blur' }]
    })
    /* 确认按钮 */
    const submitForm = (formEl: FormInstance | undefined) => {
        if (!formEl) return
        formEl.validate((valid) => {
            if (valid) {//true
                uppassword(userdui.user_id,ruleForm.pass).then(()=>{
                })
            } else {
                console.log('error submit!')
                return false
            }
        })
    }
    /*let bianliang = ref(false)
    let purview = ref(false)
    bianliang.value = false
    const beforeUpload = (file) =>{
        var testmsg = file.name.substring(file.name.lastIndexOf(".") + 1);
        const extension = testmsg === "jpg";
        if (!extension){
            ElMessage({
                message: "上传文件只能是.jpg格式",
                type: "warning",
            })
        }
        return extension;
    }
    const handleExceed = (files, fileList) =>{
        ElMessage.error(`最多上传1个版本！`);
    }

    const handleFileChange = (file, fileList) =>{
        //判断图片列表长度大于0时，代表已上传软件
        if(fileList.length > 0){
            bianliang.value = true
        }
    }
    const handleSuccess =async (response) =>{
        if(response>0){
            ElMessage({
                message: "添加版本成功！",
                type: "success",
            })
            purview.value = false
        }else {
            ElMessage.error('添加版本失败')
        }
    }*/
    const resetForm = (formEl: FormInstance | undefined) => {
        if (!formEl) return
        formEl.resetFields()
    }
    //上传头像
    const handleAvatarSuccess: UploadProps['onSuccess'] = (res, uploadFile) => {
        imageUrl.value = URL.createObjectURL(uploadFile.raw!)
        this.imageUrl = res.imageUrl
    }

    const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
        if (rawFile.type !== 'image/*') {
            ElMessage.error('头像图片必须是JPG格式!')
            return false
        } else if (rawFile.size / 1024 / 1024 > 2) {
            ElMessage.error('头像图片大小不能超过2MB!')
            return false
        }
        return true
    }
</script>
<template>
    <ElRow :gutter="20" :class="prefixCls">
        <ElCol :xl="8" :lg="8" :md="12" :sm="12" :xs="24" >
            <template #default>
                <div :class="`${prefixCls}__item flex justify-end`">
                    <ElUpload
                            ref="uploadFile"
                            class="avatar-uploader"
                            action="http://localhost:8081/upload/mainImage"
                            accept=".jpg"
                            :limit="1"
                            :auto-upload="false"
                            :before-upload="beforeAvatarUpload"
                            :on-exceed="handleExceed"
                            :on-success="handleAvatarSuccess"
                            :on-change="handleFileChange"
                            :data="{'userId': ruleForm.userId}"
                    >
                        <img  v-if="imageUrl" :src="imageUrl" class="avatar" />
                        <ElIcon v-else class="avatar-uploader-icon" :size=50>
                            ＋
                        </ElIcon>
                    </ElUpload>
                </div>
            </template>
        </ElCol>
        <ElCol :xl="12" :lg="12" :md="12" :sm="12" :xs="24" >
            <template #default>
                <div :class="`${prefixCls}__item flex`">
                    <ElForm ref="ruleFormRef"
                            :model="ruleForm"
                            :rules="rules"
                            label-width="120px"
                            class="demo-ruleForm">
                        <ElFormItem label=" 账户 ">
                            <ElInput v-model="ruleForm.name" disabled/>
                        </ElFormItem>
                        <ElFormItem label=" Email ">
                            <ElInput v-model="ruleForm.Email" disabled/>
                        </ElFormItem>
                        <ElFormItem label=" 新密码 " prop="pass">
                            <InputPassword v-model="ruleForm.pass" type="password"  strength/>
                        </ElFormItem>
                        <ElFormItem label=" 确认密码 " prop="checkPass">
                            <InputPassword v-model="ruleForm.checkPass" type="password"/>
                        </ElFormItem>
                        <ElFormItem>
                            <el-button type="primary" @click="submitForm(ruleFormRef)">确认</el-button>
                            <el-button @click="resetForm(ruleFormRef)">取消</el-button>
                        </ElFormItem>
                    </ElForm>
                </div>
            </template>
        </ElCol>
    </ElRow>
</template>
<style scoped>
    .avatar-uploader .avatar {
        width: 230px;
        height: 230px;
        display: block;
    }
    /* 定义到外边距上 */
    .el-row {
        margin-top: 100px;
        display: flex;
        flex-wrap: wrap
    }
</style>

<style>
    /* 上传图片的虚框 */
    .avatar-uploader .el-upload {
        border: 1px dashed var(--el-border-color);
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: var(--el-transition-duration-fast);
    }
    /* 鼠标停留在上传按钮那会显现出来 */
    .avatar-uploader .el-upload:hover {
        border-color: var(--el-color-primary);
    }
    /* 上传图片按钮的样式 */
    .el-icon.avatar-uploader-icon {
        color: #2d8cff;
        width: 200px;
        height: 200px;
        text-align: center;
        /* 斜体 加粗 大小/行高 字体 */
        font: italic 100 0px/200px "宋体";
    }
</style>
